package com.jiyun.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jiyun.mapper.DeptMapper;
import com.jiyun.mapper.EmpMapper;
import com.jiyun.pojo.Dept;
import com.jiyun.pojo.Emp;
import com.jiyun.pojo.EmpDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmpService {

    @Autowired
    EmpMapper empMapper;
    @Autowired
    DeptMapper deptMapper;

    public Page<Emp> findPage(Integer pageNum, Integer pageSize, EmpDTO empDTO) {
        Page<Emp> page = new Page<>(pageNum,pageSize);

        LambdaQueryWrapper<Emp> qw = new LambdaQueryWrapper<>();
        // isNotBlank isNotEmpty  判断字符串是否为空 先去掉空格，在判断
        qw.like(StringUtils.isNotBlank(empDTO.getName()),Emp::getName,empDTO.getName());
        qw.eq(empDTO.getDid()!=null,Emp::getDid,empDTO.getDid());
        qw.ge(empDTO.getDate1()!=null,Emp::getBirthday,empDTO.getDate1());
        qw.le(empDTO.getDate2()!=null,Emp::getBirthday,empDTO.getDate2());
        empMapper.selectPage(page,qw);

        List<Emp> emps = page.getRecords();
        for (Emp emp : emps) {
            // 每个员工的部门id
            Integer did = emp.getDid();
            Dept dept = deptMapper.selectById(did);
            emp.setDept(dept);
        }

        return page;
    }

    public List<Dept> findDeptList() {
        return deptMapper.selectList(null);
    }

    public void add(Emp emp) {
        empMapper.insert(emp);
    }

    public void update(Emp emp) {
        empMapper.updateById(emp);
    }

    public Emp findById(Integer id) {
        return empMapper.selectById(id);
    }

    public void deleteById(Integer id) {
        empMapper.deleteById(id);
    }

    public void deleteBatch(List<Emp> empList) {
        for (Emp emp : empList) {
            empMapper.deleteById(emp.getId());
        }
    }

    public List<Emp> findAll() {
        List<Emp> list = empMapper.selectList(null);
        for (Emp emp : list) {
            // 每个员工的部门id
            Integer did = emp.getDid();
            Dept dept = deptMapper.selectById(did);
            emp.setDeptName(dept.getName());
            emp.setSex(emp.getSex().equals("0")?"男":"女");
        }
        return list;
    }

    public Integer findByDeptName(String deptName) {
        return deptMapper.findByDeptName(deptName);
    }
}
